﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Anke.SHManage.Model.ViewModel;
using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using Anke.SHManage.MSSQLDAL;

namespace Anke.SHManage.Web.Areas.IM.Controllers
{
    public class I_EntryController : Controller
    {
        // GET: /IM/I_Entry/

        public ActionResult I_EntryList()
        {
            ViewBag.RKHC = UserOperateContext.Current.getGongneng(E_IMPermisson.RKHC);
            ViewBag.ZJXG = UserOperateContext.Current.getGongneng(E_IMPermisson.ZJXG);
            ViewBag.RK = UserOperateContext.Current.getGongneng(E_IMPermisson.RK);
            ViewBag.RKBDZJE = UserOperateContext.Current.getGongneng(E_IMPermisson.RKnoZJ);
            UserOperateContext userOperateContext = new UserOperateContext();
            bool Insert = userOperateContext.getGongneng(1312);////判断登录人有无财务审批权限 
            if (Insert)
            {
                this.ViewData["RolePermissionInsert"] = "Insert";//登录人有审批权限
            }
            else
            {
                this.ViewData["RolePermissionInsert"] = "";
            }

            this.ViewData["reMonth"] = new I_BalanceBLLExt().GetBalanceMaxReMonth();//取I_BalanceList表中最大的报表月份+1，赋给点击入账的月份

            return View();

        }


        public ActionResult I_EntryDetail()
        {
            return View();
        }
        //int page = Request.Form["page"];
        /// <summary>
        /// 查询入库流水信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult LoadEntryList()
        {

            //统计时间
            DateTime StartDate = Convert.ToDateTime(Request.Form["StartDate"]);
            DateTime EndDate = Convert.ToDateTime(Request.Form["EndDate"]);
            string EntryCode = Request.Form["EntryCode"].ToString();
            string EntryType = Request.Form["EntryType"].ToString();
            string StroageID = Request.Form["StroageID"].ToString();
            List<int> StroageIDs = new List<int>();
            if (StroageID.Length > 0)
                StroageIDs.Add(int.Parse(StroageID));
            else
                StroageIDs = UserOperateContext.Current.Session_StorageRelated.listUserStorage;

            //获取页容量
            int pageSize = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int pageIndex = int.Parse(Request.Form["page"]);

            I_EntryBLL bll = new I_EntryBLL();
            int total = 0;
            var list = bll.GetEntryList(pageIndex, pageSize, ref total, StartDate, EndDate, EntryCode, EntryType, StroageIDs);
            return Json(new { total = total, rows = list }, "appliction/json", JsonRequestBehavior.AllowGet);
            //return Json(null, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult LoadCheckEntryDetailList()
        {
            string EntryCode = Request.Form["EntryCode"].ToString();
            //新增查询是否审核 2016-4-11
            string IFCheck = Request.Form["IFCheck"].ToString();
            if (IFCheck.Length > 0)
            {
                bool sIFCheck = Convert.ToBoolean(IFCheck);
                var list = new I_EntryDetailBLL().GetListBy(e => e.EntryCode == EntryCode && e.IFCheck == sIFCheck).Select(e => e.ToExtModel());
                return Json(list, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            else
            {
                var list = new I_EntryDetailBLL().GetListBy(e => e.EntryCode == EntryCode).Select(e => e.ToExtModel());
                return Json(list, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        ///  直接入库方法 MatertalInType-1
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveEntry()
        {
            //2018-10-17 dyq 入库单号格式改变
            //  SqlConnection connection = new SqlConnection("server=IRIS-PC;uid=sa;pwd=anchor;database=AKV7Manage");
            //  SqlHelper.
            //  connection.Open();
            //  string sql = "select top 1 EntryCode from I_Entry order by OperationTime desc";
            //   SqlCommand cmd = new SqlCommand(sql, connection);
            //   SqlDataReader sdr = cmd.ExecuteReader();
            //  string card;

            //  if (sdr.Read())
            //   {
            //       card = Convert.ToString(sdr["EntryCode"]);
            //      id = Convert.ToInt32(card.Substring(card.Length - 4, 4));//截取入库单号后四位数字且转换成整数类型
            //      id++;
            //  }

            //2018-12-11 zch 修改入库编码格式 SJ + yyyyMM + 0001 方式
            //  int id = 1;
            string sEntryDetailInfo = Request.Form["sEntryDetailInfo"].ToString();
            List<EntryDetailInfo> relist = JsonHelper.GetJsonInfoBy<List<EntryDetailInfo>>(sEntryDetailInfo);
            I_Entry entryInfo = new I_Entry();
            // I_EntryBLL ieBLL = new I_EntryBLL();
            DateTime entryDate = Convert.ToDateTime(Request.Form["EntryDate"]);

            //OrderByDescending(p => p.EntryDate)
            //I_Entry maxInfo = ieBLL.GetListBy(p => p.EntryDate.Date.ToString("yyyyMM").Contains(entryDate.ToString("yyyyMM"))).FirstOrDefault();
            //if (maxInfo != null)
            //{
            //    id = Convert.ToInt32(maxInfo.EntryCode.Substring(maxInfo.EntryCode.Length - 4, 4));
            //    id++;
            //}
            // entryInfo.EntryCode = "SJ" + entryDate.ToString("yyyyMM") + id.ToString().PadLeft(4, '0'); //四位数不够补0；    //生成入库编码//2018-10-17 dyq 入库单号格式改变

            entryInfo.EntryDate = entryDate;
            entryInfo.EntryType = "MatertalInType-1";
            entryInfo.OperationTime = DateTime.Now;
            entryInfo.OperatorCode = UserOperateContext.Current.Session_UsrInfo.ID;
            entryInfo.EntryStorageID = int.Parse(Request.Form["StorageCode"]);
            entryInfo.Remark = Request.Form["Remark"].ToString().Trim();
            List<I_EntryDetail> list = new List<Model.I_EntryDetail>();
            //  int ind = 0;
            foreach (EntryDetailInfo item in relist)
            {
                //  ind++;
                I_EntryDetail detailinfo = new I_EntryDetail();

                //detailinfo.EntryDetailCode = entryInfo.EntryCode + entryInfo.OperatorCode + ind.ToString();
                detailinfo.BatchNo = item.BatchNo;
                detailinfo.RealBatchNo = item.RealBatchNo;
               // detailinfo.EntryCode = entryInfo.EntryCode;
                detailinfo.EntryCounts = item.EntryCounts;
                detailinfo.EntryDate = item.EntryDate;
                detailinfo.MaterialID = item.MaterialID;
                detailinfo.OperatorCode = UserOperateContext.Current.Session_UsrInfo.ID;
                detailinfo.RedEntryDetailCode = "";
                detailinfo.RelatedOrderNum = item.RelatedOrderNum;
                detailinfo.Remark = item.Remark.Trim();
                detailinfo.Specification = item.Specification;
                detailinfo.StorageCode = item.StorageCode;
                detailinfo.TotalPrice = item.TotalPrice;
                detailinfo.Unit = item.Unit;
                //detailinfo.TargerUserID = UserOperateContext.Current.Session_UsrInfo.ID;
                //2016-4-11 将是否审核默认为未审核
                detailinfo.IFCheck = false;
                if (item.ValidityDateStr == "无有效期")
                    detailinfo.ValidityDate = DateTime.MaxValue;
                else
                    detailinfo.ValidityDate = Convert.ToDateTime(item.ValidityDateStr);
                list.Add(detailinfo);
            }
            string errorMsg = "";
            if (new I_EntryBLL().EntryOperate(entryInfo, list, ref errorMsg))
                return this.JsonResult(Utility.E_JsonResult.OK, "入库信息成功！", null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, errorMsg, null, null);
        }


        public ActionResult SaveRedEntryDetiail()
        {
            string EntryDetailCode = Request.Form["EntryDetailCode"].ToString();
            string EntryRemark = Request.Form["EntryRemark"].ToString();
            int StroageCode = int.Parse(Request.Form["StroageCode"]);
            string errorMsg = "";
            if (new I_EntryBLL().EntryRedOperate(EntryDetailCode, EntryRemark, StroageCode, ref errorMsg))
                return this.JsonResult(Utility.E_JsonResult.OK, "红冲入库信息成功！", null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, errorMsg, null, null);
        }

        public ActionResult EditEntryTotalPriceDetiail()
        {
            string EntryDetailCode = Request.Form["EntryDetailCode"].ToString();
            decimal TotalPrice = Convert.ToDecimal(Request.Form["TotalPrice"]);
            string EntryRemark = Request.Form["EntryRemark"].ToString();
            string errorMsg = "";
            Model.I_EntryDetail info = new I_EntryDetail();
            info.EntryDetailCode = EntryDetailCode;
            info.Remark = EntryRemark;
            info.TotalPrice = TotalPrice;
            if (new I_EntryBLL().EditEntryDetail(info, ref errorMsg))
                return this.JsonResult(Utility.E_JsonResult.OK, "修改价格成功！", null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, errorMsg, null, null);
        }



        //2016-4-9新增 财务审批入库
        [HttpPost]
        public ActionResult EntryCheckSave()
        {
            string tempReportMonth = Request.Form["ReportMonth"].ToString();

            string sEntryDetailInfo = Request.Form["sEntryDetailInfo"].ToString();
            List<I_EntryDetail> relist = JsonHelper.GetJsonInfoBy<List<I_EntryDetail>>(sEntryDetailInfo); //前台传来的从表数据

            if (relist.Count > 0)
            {
                DateTime tempNow = DateTime.Now;
                int resultentryDetail = relist.Count; int resultInventoryRecord = relist.Count;
                //循环将入库字表的IFcheck和CheckTime值改变
                for (int i = 0; i < relist.Count; i++)
                {
                    string tempEntryDetailCode = relist[i].EntryDetailCode;
                    //先根据EntryDetailCode 将实体取出来，看是否存在IFCHECK 和CheckTime 如果存在就不更改
                    I_EntryDetail entryDetailinfo = new I_EntryDetailBLL().GetModelWithOutTrace(p => p.EntryDetailCode == tempEntryDetailCode);

                    if (entryDetailinfo.IFCheck != true || entryDetailinfo.IFCheck == null) //判断是否有I_EntryDetail 
                    {
                        entryDetailinfo.IFCheck = true;
                        entryDetailinfo.CheckTime = tempNow;
                        entryDetailinfo.ReportMonth = tempReportMonth;

                        int resultDetail = new I_EntryDetailBLL().Modify(entryDetailinfo, "IFCheck", "CheckTime", "ReportMonth");
                        resultentryDetail = resultentryDetail + resultDetail;


                    }
                    else
                    {
                        //return this.JsonResult(Utility.E_JsonResult.Error, "对不起，已审核过，无法重复审核！", null, null);
                    }
                    //把Record 中的EntryDetailCode 那一条取出来，再更改IFCheck，CheckTime
                    I_InventoryRecord inInfo = new I_InventoryRecordBLL().GetModelWithOutTrace(p => p.EntryDetailCode == tempEntryDetailCode);

                    if (inInfo.IFCheck != true || inInfo.IFCheck == null)  //判断是否有Record
                    {
                        inInfo.IFCheck = true;
                        inInfo.CheckTime = tempNow;
                        inInfo.ReportMonth = tempReportMonth;
                        int resultRecord = new I_InventoryRecordBLL().Modify(inInfo, "IFCheck", "CheckTime", "ReportMonth");
                        resultInventoryRecord = resultInventoryRecord + resultRecord;
                    }
                    else
                    {
                        //return Json("");
                    }

                }
                if (resultentryDetail >= relist.Count && resultInventoryRecord >= relist.Count)
                {
                    return this.JsonResult(Utility.E_JsonResult.OK, "入账成功！", null, null);
                }
                else
                {
                    return this.JsonResult(Utility.E_JsonResult.Error, "入账失败！", null, null);
                }
            }
            else
            {
                return Json("");
            }

        }
    }

}
